<template>
  <NDrawer v-model:show="visible" :width="720" :title="title">
    <NDrawerContent closable>
      <NForm ref="formRef" :model="formModel" :rules="rules" label-placement="left" :label-width="100">
        <NFormItem label="规则名称" path="name">
          <NInput v-model:value="formModel.name" placeholder="请输入规则名称" />
        </NFormItem>
        <NFormItem label="规则编码" path="code">
          <NInput v-model:value="formModel.code" placeholder="请输入规则编码" />
        </NFormItem>
        <NFormItem label="质量维度" path="dimension">
          <NSelect v-model:value="formModel.dimension" :options="dimensionOptions" placeholder="请选择质量维度" />
        </NFormItem>
        <NFormItem label="清洗类型" path="cleanType">
          <NSelect v-model:value="formModel.cleanType" :options="cleanTypeOptions" placeholder="请选择清洗类型" />
        </NFormItem>
        <NFormItem label="清洗逻辑" path="cleanLogic">
          <NInput
            v-model:value="formModel.cleanLogic"
            type="textarea"
            :rows="6"
            placeholder="请输入清洗逻辑（JSON格式）"
          />
        </NFormItem>
        <NFormItem label="优先级" path="priority">
          <NInputNumber v-model:value="formModel.priority" :min="1" :max="100" placeholder="请输入优先级" />
        </NFormItem>
        <NFormItem label="描述" path="description">
          <NInput v-model:value="formModel.description" type="textarea" :rows="3" placeholder="请输入描述" />
        </NFormItem>
        <NFormItem label="使用场景" path="useCase">
          <NInput v-model:value="formModel.useCase" type="textarea" :rows="2" placeholder="请输入使用场景" />
        </NFormItem>
        <NFormItem label="示例" path="example">
          <NInput v-model:value="formModel.example" type="textarea" :rows="2" placeholder="请输入示例" />
        </NFormItem>
        <NFormItem label="状态" path="status">
          <NRadioGroup v-model:value="formModel.status">
            <NRadio :value="1">启用</NRadio>
            <NRadio :value="0">禁用</NRadio>
          </NRadioGroup>
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace justify="end">
          <NButton @click="closeDrawer">取消</NButton>
          <NButton type="primary" :loading="submitLoading" @click="handleSubmit">确定</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue';
import type { FormInst, FormRules } from 'naive-ui';
import { addCleanRule, updateCleanRule, fetchCleanRuleDetail } from '@/service/api';

export type ModalType = 'add' | 'edit';

interface Props {
  visible: boolean;
  operateType: ModalType;
  rowData?: { id: number } | null;
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  operateType: 'add',
  rowData: null
});

interface Emits {
  (e: 'update:visible', visible: boolean): void;
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = computed({
  get: () => props.visible,
  set: val => emit('update:visible', val)
});

const title = computed(() => (props.operateType === 'add' ? '新增清洗规则' : '编辑清洗规则'));

const formRef = ref<FormInst | null>(null);
const submitLoading = ref(false);

const formModel = reactive({
  id: undefined as number | undefined,
  name: '',
  code: '',
  dimension: '',
  cleanType: '',
  cleanLogic: '',
  priority: 10,
  description: '',
  useCase: '',
  example: '',
  status: 1
});

const dimensionOptions = [
  { label: '准确性', value: 'ACCURACY' },
  { label: '完整性', value: 'COMPLETENESS' },
  { label: '一致性', value: 'CONSISTENCY' },
  { label: '唯一性', value: 'UNIQUENESS' },
  { label: '有效性', value: 'VALIDITY' },
  { label: '及时性', value: 'TIMELINESS' }
];

const cleanTypeOptions = [
  { label: '去重', value: 'DEDUPLICATE' },
  { label: '填补空值', value: 'FILL_NULL' },
  { label: '格式标准化', value: 'FORMAT_NORMALIZE' },
  { label: '异常值处理', value: 'OUTLIER_HANDLE' },
  { label: '单位统一', value: 'UNIT_UNIFY' },
  { label: '编码统一', value: 'CODE_UNIFY' }
];

const rules: FormRules = {
  name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
  code: [{ required: true, message: '请输入规则编码', trigger: 'blur' }],
  dimension: [{ required: true, message: '请选择质量维度', trigger: 'change' }],
  cleanType: [{ required: true, message: '请选择清洗类型', trigger: 'change' }],
  cleanLogic: [{ required: true, message: '请输入清洗逻辑', trigger: 'blur' }],
  priority: [{ required: true, type: 'number', message: '请输入优先级', trigger: 'blur' }]
};

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await formRef.value?.validate();
  submitLoading.value = true;
  try {
    if (props.operateType === 'add') {
      await addCleanRule(formModel);
      window.$message?.success('新增成功');
    } else {
      await updateCleanRule(formModel);
      window.$message?.success('更新成功');
    }
    closeDrawer();
    emit('submitted');
  } finally {
    submitLoading.value = false;
  }
}

async function loadDetail() {
  if (props.operateType === 'edit' && props.rowData?.id) {
    const data = await fetchCleanRuleDetail(props.rowData.id);
    Object.assign(formModel, data.data);
  }
}

function resetForm() {
  formModel.id = undefined;
  formModel.name = '';
  formModel.code = '';
  formModel.dimension = '';
  formModel.cleanType = '';
  formModel.cleanLogic = '';
  formModel.priority = 10;
  formModel.description = '';
  formModel.useCase = '';
  formModel.example = '';
  formModel.status = 1;
}

watch(visible, val => {
  if (val) {
    if (props.operateType === 'edit') {
      loadDetail();
    } else {
      resetForm();
    }
  }
});
</script>

<style scoped></style>
